#define _DEFAULT_SOURCE

#include "apue.h"
#include <stdlib.h>
#include <unistd.h>
#include <aio.h>
#include <errno.h>
#define BSZ 5 


int main(void) {
    int err, nrd, eof;
    struct aiocb ai;
    int status= 0;
    ai.aio_buf= (char *)malloc(BSZ * sizeof(char));
    ai.aio_sigevent.sigev_notify= SIGEV_NONE;
    eof= 0;

    while (!eof) {
        ai.aio_fildes= STDIN_FILENO;
        ai.aio_nbytes= BSZ;
        if (aio_read(&ai) < 0)
            err_sys("aio_read failed");
        // printf("\n-read-\n");

        status = 0;
        while(status < 2) {
            if ((err= aio_error(&ai)) == EINPROGRESS)
                continue;
            if (err != 0) {
                if (err == -1)
                    err_sys("aio_error failed");
                else 
                    err_exit(err, "read failed");
            }
            
            if (++status == 1 && (nrd= aio_return(&ai)) == 0) {  //EOF
                eof= 1;                                
                break;
            }
            //if (status == 1)
            //    printf("\n%s %d chars\n", status == 1 ? "read" : "write", nrd);
            if (status == 1) {
                ai.aio_fildes= STDOUT_FILENO;
                ai.aio_nbytes= nrd;
                aio_write(&ai);
            }
        }
    }
    exit(0);
}
